Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.
In [2]:
print(dog_names)
['Affenpinscher', 'Afghan_hound', 'Airedale_terrier', 'Akita', 'Alaskan_malamute', 'American_eskimo_dog', 'American_foxhound', 'American_staffordshire_terrier', 'American_water_spaniel', 'Anatolian_shepherd_dog', 'Australian_cattle_dog', 'Australian_shepherd', 'Australian_terrier', 'Basenji', 'Basset_hound', 'Beagle', 'Bearded_collie', 'Beauceron', 'Bedlington_terrier', 'Belgian_malinois', 'Belgian_sheepdog', 'Belgian_tervuren', 'Bernese_mountain_dog', 'Bichon_frise', 'Black_and_tan_coonhound', 'Black_russian_terrier', 'Bloodhound', 'Bluetick_coonhound', 'Border_collie', 'Border_terrier', 'Borzoi', 'Boston_terrier', 'Bouvier_des_flandres', 'Boxer', 'Boykin_spaniel', 'Briard', 'Brittany', 'Brussels_griffon', 'Bull_terrier', 'Bulldog', 'Bullmastiff', 'Cairn_terrier', 'Canaan_dog', 'Cane_corso', 'Cardigan_welsh_corgi', 'Cavalier_king_charles_spaniel', 'Chesapeake_bay_retriever', 'Chihuahua', 'Chinese_crested', 'Chinese_shar-pei', 'Chow_chow', 'Clumber_spaniel', 'Cocker_spaniel', 'Collie', 'Curly-coated_retriever', 'Dachshund', 'Dalmatian', 'Dandie_dinmont_terrier', 'Doberman_pinscher', 'Dogue_de_bordeaux', 'English_cocker_spaniel', 'English_setter', 'English_springer_spaniel', 'English_toy_spaniel', 'Entlebucher_mountain_dog', 'Field_spaniel', 'Finnish_spitz', 'Flat-coated_retriever', 'French_bulldog', 'German_pinscher', 'German_shepherd_dog', 'German_shorthaired_pointer', 'German_wirehaired_pointer', 'Giant_schnauzer', 'Glen_of_imaal_terrier', 'Golden_retriever', 'Gordon_setter', 'Great_dane', 'Great_pyrenees', 'Greater_swiss_mountain_dog', 'Greyhound', 'Havanese', 'Ibizan_hound', 'Icelandic_sheepdog', 'Irish_red_and_white_setter', 'Irish_setter', 'Irish_terrier', 'Irish_water_spaniel', 'Irish_wolfhound', 'Italian_greyhound', 'Japanese_chin', 'Keeshond', 'Kerry_blue_terrier', 'Komondor', 'Kuvasz', 'Labrador_retriever', 'Lakeland_terrier', 'Leonberger', 'Lhasa_apso', 'Lowchen', 'Maltese', 'Manchester_terrier', 'Mastiff', 'Miniature_schnauzer', 'Neapolitan_mastiff', 'Newfoundland', 'Norfolk_terrier', 'Norwegian_buhund', 'Norwegian_elkhound', 'Norwegian_lundehund', 'Norwich_terrier', 'Nova_scotia_duck_tolling_retriever', 'Old_english_sheepdog', 'Otterhound', 'Papillon', 'Parson_russell_terrier', 'Pekingese', 'Pembroke_welsh_corgi', 'Petit_basset_griffon_vendeen', 'Pharaoh_hound', 'Plott', 'Pointer', 'Pomeranian', 'Poodle', 'Portuguese_water_dog', 'Saint_bernard', 'Silky_terrier', 'Smooth_fox_terrier', 'Tibetan_mastiff', 'Welsh_springer_spaniel', 'Wirehaired_pointing_griffon', 'Xoloitzcuintli', 'Yorkshire_terrier']

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [3]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [4]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [5]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

99% of the first 100 images in human_files have a detected human face.

11% of the first 100 images in dog_files have a detected human face.

NOTE: all we need to do is to get the count since we have 100 images so percentage calculation is moot.

In [6]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

humans = 0

for img in human_files_short:
    if (face_detector(img) == True):
        humans = humans + 1
        
dogs = 0

for img in dog_files_short:
    if (face_detector(img) == True):
        dogs = dogs + 1
        
print('There are %d total humans.' % humans)
print('There are %d total dogs.' % dogs)
There are 99 total humans.
There are 11 total dogs.

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

For the time being, i believe this is an acceptable limitation. It might be OK to tell the user to provide a clear view of the face.

Good reasons for using Haar Cascades can be found at https://docs.opencv.org/3.3.0/d7/d8b/tutorial_py_face_detection.html

However there are 2 forces in play here. Users are going to be more and more demanding and there will be several advances in machine learning as well where we will be able to train several more types of images with side on views and faces at an angle. Along with image augmentation techniques we will be able to correctly detect faces/images that are not fully clear. Example, say we have a side view of a human. This will have only 1 eye or say the person is looking at an angle, we should be able to correctly detect with even these images.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [7]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [8]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [9]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [10]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [11]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

0% of the first 100 images in human_files have a detected dog.

100% of the first 100 images in dog_files have a detected dog.

Just as mentioned above, all we need to do is to get the count since we have 100 images so percentage calculation is moot.

In [12]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

humans = 0

for img in human_files_short:
    if (dog_detector(img) == True):
        humans = humans + 1
        
dogs = 0

for img in dog_files_short:
    if (dog_detector(img) == True):
        dogs = dogs + 1
        
print('There are %d total humans.' % humans)
print('There are %d total dogs.' % dogs)
There are 0 total humans.
There are 100 total dogs.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [13]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [00:58<00:00, 113.37it/s]
100%|██████████| 835/835 [00:06<00:00, 127.35it/s]
100%|██████████| 836/836 [00:06<00:00, 128.36it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

First i would like to say that though the architecture below is very similar to the example CNN architecture provided, i have done other CNNs in several projects where progressively increasing the filter size in powers of 2 has given me good results. I use 4 convolution layers and progressively increase filter size from 16 to 32 to 64 to 128. This will greatly help in extracting the features. After every convolution layer i add a max pooling layer to reduce dimensionality. In some example runs of the CNN i did try using dropout and more connected layers but that did not improve the model. I even tried to use "same" padding but that too didn't improve the model. I do global average pooling followed by a fully connected layer. Since we have 133 different dog breeds, the final layer will have 133 nodes. Care should be taken to use a softmax activation function in the final connected layer. The number of epochs I used was equal to 20

In [14]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(filters=16, kernel_size=2, padding='valid', strides = 1,input_shape=(224, 224, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(filters=32, kernel_size=2, padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(filters=64, kernel_size=2, padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(filters=128, kernel_size=2, padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

#model.add(Dropout(0.2))
#model.add(Flatten())
#model.add(Dense(500, activation='relu')) 
#model.add(Dropout(0.2))

model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 223, 223, 16)      208       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 111, 111, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 110, 110, 32)      2080      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 55, 55, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 54, 54, 64)        8256      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 27, 27, 64)        0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 26, 26, 128)       32896     
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 13, 13, 128)       0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 128)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               17157     
=================================================================
Total params: 60,597.0
Trainable params: 60,597.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [19]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [19]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 20

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.8832 - acc: 0.0084Epoch 00000: val_loss improved from inf to 4.85865, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 37s - loss: 4.8831 - acc: 0.0084 - val_loss: 4.8587 - val_acc: 0.0144
Epoch 2/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.8178 - acc: 0.0173Epoch 00001: val_loss improved from 4.85865 to 4.77306, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.8175 - acc: 0.0172 - val_loss: 4.7731 - val_acc: 0.0156
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.7401 - acc: 0.0215Epoch 00002: val_loss improved from 4.77306 to 4.75398, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.7393 - acc: 0.0216 - val_loss: 4.7540 - val_acc: 0.0216
Epoch 4/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.6805 - acc: 0.0285Epoch 00003: val_loss improved from 4.75398 to 4.69476, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.6800 - acc: 0.0284 - val_loss: 4.6948 - val_acc: 0.0192
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.6281 - acc: 0.0335Epoch 00004: val_loss improved from 4.69476 to 4.65710, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.6279 - acc: 0.0335 - val_loss: 4.6571 - val_acc: 0.0287
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.5717 - acc: 0.0432Epoch 00005: val_loss improved from 4.65710 to 4.57545, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.5717 - acc: 0.0434 - val_loss: 4.5755 - val_acc: 0.0467
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.5070 - acc: 0.0503Epoch 00006: val_loss improved from 4.57545 to 4.53229, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s - loss: 4.5066 - acc: 0.0501 - val_loss: 4.5323 - val_acc: 0.0419
Epoch 8/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.4377 - acc: 0.0551Epoch 00007: val_loss improved from 4.53229 to 4.47970, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s - loss: 4.4374 - acc: 0.0552 - val_loss: 4.4797 - val_acc: 0.0407
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.3797 - acc: 0.0607Epoch 00008: val_loss improved from 4.47970 to 4.41288, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s - loss: 4.3800 - acc: 0.0606 - val_loss: 4.4129 - val_acc: 0.0623
Epoch 10/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.3205 - acc: 0.0671Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 35s - loss: 4.3204 - acc: 0.0671 - val_loss: 4.4364 - val_acc: 0.0503
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.2654 - acc: 0.0730Epoch 00010: val_loss improved from 4.41288 to 4.35943, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.2649 - acc: 0.0729 - val_loss: 4.3594 - val_acc: 0.0575
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.2145 - acc: 0.0782Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 35s - loss: 4.2139 - acc: 0.0781 - val_loss: 4.4513 - val_acc: 0.0623
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.1737 - acc: 0.0841Epoch 00012: val_loss improved from 4.35943 to 4.23167, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s - loss: 4.1734 - acc: 0.0840 - val_loss: 4.2317 - val_acc: 0.0695
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.1349 - acc: 0.0884Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 35s - loss: 4.1349 - acc: 0.0883 - val_loss: 4.2373 - val_acc: 0.0731
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.0949 - acc: 0.0877Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 36s - loss: 4.0953 - acc: 0.0877 - val_loss: 4.2432 - val_acc: 0.0754
Epoch 16/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.0580 - acc: 0.0962Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 35s - loss: 4.0573 - acc: 0.0964 - val_loss: 4.2364 - val_acc: 0.0802
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.0264 - acc: 0.0989Epoch 00016: val_loss improved from 4.23167 to 4.16990, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 4.0279 - acc: 0.0987 - val_loss: 4.1699 - val_acc: 0.0802
Epoch 18/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.9912 - acc: 0.1042Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 35s - loss: 3.9907 - acc: 0.1043 - val_loss: 4.2540 - val_acc: 0.0790
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.9692 - acc: 0.1123Epoch 00018: val_loss improved from 4.16990 to 4.16716, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s - loss: 3.9678 - acc: 0.1126 - val_loss: 4.1672 - val_acc: 0.0886
Epoch 20/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.9390 - acc: 0.1129Epoch 00019: val_loss improved from 4.16716 to 4.15060, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s - loss: 3.9380 - acc: 0.1132 - val_loss: 4.1506 - val_acc: 0.0994
Out[19]:
<keras.callbacks.History at 0x7f8ffde6b908>

Load the Model with the Best Validation Loss

In [20]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [21]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 9.8086%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [22]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [23]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [24]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [25]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6600/6680 [============================>.] - ETA: 0s - loss: 11.8516 - acc: 0.1382Epoch 00000: val_loss improved from inf to 10.11216, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 11.8488 - acc: 0.1383 - val_loss: 10.1122 - val_acc: 0.2551
Epoch 2/20
6520/6680 [============================>.] - ETA: 0s - loss: 9.5922 - acc: 0.3035Epoch 00001: val_loss improved from 10.11216 to 9.33425, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.5562 - acc: 0.3057 - val_loss: 9.3343 - val_acc: 0.3222
Epoch 3/20
6520/6680 [============================>.] - ETA: 0s - loss: 8.9542 - acc: 0.3745Epoch 00002: val_loss improved from 9.33425 to 9.17825, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.9686 - acc: 0.3725 - val_loss: 9.1783 - val_acc: 0.3449
Epoch 4/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.7912 - acc: 0.4014Epoch 00003: val_loss improved from 9.17825 to 9.11836, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.7794 - acc: 0.4016 - val_loss: 9.1184 - val_acc: 0.3665
Epoch 5/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.6310 - acc: 0.4221Epoch 00004: val_loss improved from 9.11836 to 8.94110, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6427 - acc: 0.4213 - val_loss: 8.9411 - val_acc: 0.3749
Epoch 6/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.4499 - acc: 0.4392Epoch 00005: val_loss improved from 8.94110 to 8.91571, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.4276 - acc: 0.4404 - val_loss: 8.9157 - val_acc: 0.3772
Epoch 7/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.2023 - acc: 0.4580Epoch 00006: val_loss improved from 8.91571 to 8.64175, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.2138 - acc: 0.4575 - val_loss: 8.6417 - val_acc: 0.3964
Epoch 8/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.9812 - acc: 0.4717Epoch 00007: val_loss improved from 8.64175 to 8.44271, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.9764 - acc: 0.4719 - val_loss: 8.4427 - val_acc: 0.3856
Epoch 9/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.7055 - acc: 0.4922Epoch 00008: val_loss improved from 8.44271 to 8.21258, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.6958 - acc: 0.4933 - val_loss: 8.2126 - val_acc: 0.4251
Epoch 10/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.5962 - acc: 0.5083Epoch 00009: val_loss improved from 8.21258 to 8.17704, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.6004 - acc: 0.5082 - val_loss: 8.1770 - val_acc: 0.4251
Epoch 11/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.4609 - acc: 0.5203Epoch 00010: val_loss improved from 8.17704 to 8.02188, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.4727 - acc: 0.5198 - val_loss: 8.0219 - val_acc: 0.4251
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.3454 - acc: 0.5231Epoch 00011: val_loss improved from 8.02188 to 7.96427, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.3427 - acc: 0.5234 - val_loss: 7.9643 - val_acc: 0.4240
Epoch 13/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.1250 - acc: 0.5363Epoch 00012: val_loss improved from 7.96427 to 7.80145, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.1240 - acc: 0.5364 - val_loss: 7.8015 - val_acc: 0.4287
Epoch 14/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.0451 - acc: 0.5419Epoch 00013: val_loss improved from 7.80145 to 7.71877, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.0261 - acc: 0.5433 - val_loss: 7.7188 - val_acc: 0.4443
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 6.8674 - acc: 0.5500Epoch 00014: val_loss improved from 7.71877 to 7.60686, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.8543 - acc: 0.5507 - val_loss: 7.6069 - val_acc: 0.4527
Epoch 16/20
6560/6680 [============================>.] - ETA: 0s - loss: 6.7262 - acc: 0.5623Epoch 00015: val_loss improved from 7.60686 to 7.49003, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.7065 - acc: 0.5635 - val_loss: 7.4900 - val_acc: 0.4587
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 6.5445 - acc: 0.5757Epoch 00016: val_loss improved from 7.49003 to 7.37883, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.5516 - acc: 0.5753 - val_loss: 7.3788 - val_acc: 0.4599
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 6.4795 - acc: 0.5870Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 6.4769 - acc: 0.5873 - val_loss: 7.3933 - val_acc: 0.4707
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 6.3706 - acc: 0.5918Epoch 00018: val_loss improved from 7.37883 to 7.26757, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.3782 - acc: 0.5912 - val_loss: 7.2676 - val_acc: 0.4707
Epoch 20/20
6600/6680 [============================>.] - ETA: 0s - loss: 6.3120 - acc: 0.5994Epoch 00019: val_loss improved from 7.26757 to 7.20823, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.3093 - acc: 0.5996 - val_loss: 7.2082 - val_acc: 0.4790
Out[25]:
<keras.callbacks.History at 0x7f8fd0736c50>

Load the Model with the Best Validation Loss

In [26]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [27]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 47.2488%

Predict Dog Breed with the Model

In [15]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [16]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features['train']
valid_VGG19 = bottleneck_features['valid']
test_VGG19 = bottleneck_features['test']

bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_RESNET50 = bottleneck_features['train']
valid_RESNET50 = bottleneck_features['valid']
test_RESNET50 = bottleneck_features['test']

bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_XCEPTION = bottleneck_features['train']
valid_XCEPTION = bottleneck_features['valid']
test_XCEPTION = bottleneck_features['test']

bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')
train_INCEPTIONV3 = bottleneck_features['train']
valid_INCEPTIONV3 = bottleneck_features['valid']
test_INCEPTIONV3 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

I decided to try all the 4 other suggested models. I decided to keep things simple by just add a Global Average Polling layer and a solitary dense layer.

Here are the various test test accuracies.

VGG16 ==> : 47.2488%

VGG19 ==> : 44.9761%

RESNET50 ==> : 80.8612%

INCEPTIONV3 ==> : 78.4689%

XCEPTION ==> : 84.9282%%

Hence, i decide to pursue Xception as my model of choice to test unknown images from google images. I increased the number of epochs to 30 but got very marginal improvement. i changed the optimizer to sgd from rmsprop and even tuned the hyperparameter but got a very marginal improvement.

There were other reasons as well for going forward with Xception. It improves on Inception V3 and is proposed by the Francois Chollet himself. Xception performs better than Inception V3 on the ImageNEt data as well.

XCEPTION PAPER

The Documentation at https://keras.io/optimizers/ says that it is better to leave the RMSprop optimzer parameters at their default values so i decided to try SGD. The Xception paper also talks about this.

The main reason for going forward with Xception is becuase it heavily builds on previous architectures such as VGG 16 and Inception. It also uses depthwise separable convolutions. Using transfer learning greatly speeds up the training.

In [30]:
### TODO: Define your architecture.
VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(133, activation='softmax'))

VGG19_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [31]:
### TODO: Compile the model.
VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [32]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6640/6680 [============================>.] - ETA: 0s - loss: 11.5839 - acc: 0.1441Epoch 00000: val_loss improved from inf to 9.78045, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 11.5756 - acc: 0.1443 - val_loss: 9.7805 - val_acc: 0.2719
Epoch 2/20
6500/6680 [============================>.] - ETA: 0s - loss: 9.2448 - acc: 0.3214Epoch 00001: val_loss improved from 9.78045 to 9.22179, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 9.2311 - acc: 0.3223 - val_loss: 9.2218 - val_acc: 0.3234
Epoch 3/20
6500/6680 [============================>.] - ETA: 0s - loss: 8.6870 - acc: 0.3906Epoch 00002: val_loss improved from 9.22179 to 8.89909, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 8.7053 - acc: 0.3895 - val_loss: 8.8991 - val_acc: 0.3557
Epoch 4/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.3072 - acc: 0.4293Epoch 00003: val_loss improved from 8.89909 to 8.66834, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 8.3127 - acc: 0.4289 - val_loss: 8.6683 - val_acc: 0.3713
Epoch 5/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.0735 - acc: 0.4559Epoch 00004: val_loss improved from 8.66834 to 8.54660, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 8.0835 - acc: 0.4555 - val_loss: 8.5466 - val_acc: 0.3928
Epoch 6/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.9636 - acc: 0.4728Epoch 00005: val_loss improved from 8.54660 to 8.44317, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.9531 - acc: 0.4738 - val_loss: 8.4432 - val_acc: 0.4120
Epoch 7/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.7771 - acc: 0.4910Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.8138 - acc: 0.4888 - val_loss: 8.4878 - val_acc: 0.3940
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.7626 - acc: 0.5002Epoch 00007: val_loss improved from 8.44317 to 8.42835, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.7743 - acc: 0.4994 - val_loss: 8.4283 - val_acc: 0.3964
Epoch 9/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.7567 - acc: 0.5036Epoch 00008: val_loss improved from 8.42835 to 8.37194, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.7500 - acc: 0.5034 - val_loss: 8.3719 - val_acc: 0.4096
Epoch 10/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.7206 - acc: 0.5079Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.7236 - acc: 0.5078 - val_loss: 8.3757 - val_acc: 0.4180
Epoch 11/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.6365 - acc: 0.5140Epoch 00010: val_loss improved from 8.37194 to 8.29691, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.6296 - acc: 0.5144 - val_loss: 8.2969 - val_acc: 0.4216
Epoch 12/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.5966 - acc: 0.5204Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.6015 - acc: 0.5202 - val_loss: 8.3990 - val_acc: 0.4108
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.5831 - acc: 0.5215Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.5869 - acc: 0.5213 - val_loss: 8.3227 - val_acc: 0.4216
Epoch 14/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.5693 - acc: 0.5198Epoch 00013: val_loss improved from 8.29691 to 8.24886, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.5436 - acc: 0.5213 - val_loss: 8.2489 - val_acc: 0.4156
Epoch 15/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.3725 - acc: 0.5322Epoch 00014: val_loss improved from 8.24886 to 8.04837, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.3949 - acc: 0.5307 - val_loss: 8.0484 - val_acc: 0.4335
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.2822 - acc: 0.5400Epoch 00015: val_loss improved from 8.04837 to 8.02977, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.2722 - acc: 0.5407 - val_loss: 8.0298 - val_acc: 0.4371
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.2250 - acc: 0.5440Epoch 00016: val_loss improved from 8.02977 to 7.98642, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.2202 - acc: 0.5443 - val_loss: 7.9864 - val_acc: 0.4311
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.1595 - acc: 0.5473Epoch 00017: val_loss improved from 7.98642 to 7.89424, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.1643 - acc: 0.5467 - val_loss: 7.8942 - val_acc: 0.4515
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.0875 - acc: 0.5508Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 7.0999 - acc: 0.5500 - val_loss: 7.9642 - val_acc: 0.4407
Epoch 20/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.0088 - acc: 0.5558Epoch 00019: val_loss improved from 7.89424 to 7.84331, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.0015 - acc: 0.5563 - val_loss: 7.8433 - val_acc: 0.4563
Out[32]:
<keras.callbacks.History at 0x7f8fd0528f60>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [33]:
### TODO: Load the model weights with the best validation loss.
VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [34]:
### TODO: Calculate classification accuracy on the test dataset.
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 44.9761%

XCEPTION

In [17]:
from keras import optimizers

XCEPTION_model = Sequential()
XCEPTION_model.add(GlobalAveragePooling2D(input_shape=train_XCEPTION.shape[1:]))
XCEPTION_model.add(Dense(532, activation='relu'))
XCEPTION_model.add(Dense(133, activation='softmax'))

XCEPTION_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 2048)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 532)               1090068   
_________________________________________________________________
dense_3 (Dense)              (None, 133)               70889     
=================================================================
Total params: 1,160,957.0
Trainable params: 1,160,957.0
Non-trainable params: 0.0
_________________________________________________________________

COMPILE XCEPTION

In [18]:
sgd = optimizers.SGD(lr=0.001, decay=1e-6, momentum=0.8, nesterov=True)
#sgd = optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)

XCEPTION_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

TRAIN XCEPTION

In [33]:
from keras.callbacks import ModelCheckpoint

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.XCEPTION.hdf5', 
                               verbose=1, save_best_only=True)

XCEPTION_model.fit(train_XCEPTION, train_targets, 
          validation_data=(valid_XCEPTION, valid_targets),
          epochs=30, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.4314 - acc: 0.2062Epoch 00000: val_loss improved from inf to 3.82571, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 4.4297 - acc: 0.2069 - val_loss: 3.8257 - val_acc: 0.4946
Epoch 2/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.2018 - acc: 0.5943Epoch 00001: val_loss improved from 3.82571 to 2.58092, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 3.1999 - acc: 0.5949 - val_loss: 2.5809 - val_acc: 0.6539
Epoch 3/30
6660/6680 [============================>.] - ETA: 0s - loss: 2.0635 - acc: 0.7114Epoch 00002: val_loss improved from 2.58092 to 1.67693, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 2.0625 - acc: 0.7114 - val_loss: 1.6769 - val_acc: 0.7425
Epoch 4/30
6640/6680 [============================>.] - ETA: 0s - loss: 1.3746 - acc: 0.7782Epoch 00003: val_loss improved from 1.67693 to 1.20731, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 1.3733 - acc: 0.7781 - val_loss: 1.2073 - val_acc: 0.7892
Epoch 5/30
6660/6680 [============================>.] - ETA: 0s - loss: 1.0231 - acc: 0.8204Epoch 00004: val_loss improved from 1.20731 to 0.96443, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 1.0216 - acc: 0.8208 - val_loss: 0.9644 - val_acc: 0.8024
Epoch 6/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.8304 - acc: 0.8428Epoch 00005: val_loss improved from 0.96443 to 0.82774, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.8308 - acc: 0.8427 - val_loss: 0.8277 - val_acc: 0.8228
Epoch 7/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.7148 - acc: 0.8559Epoch 00006: val_loss improved from 0.82774 to 0.74828, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.7142 - acc: 0.8561 - val_loss: 0.7483 - val_acc: 0.8323
Epoch 8/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.6392 - acc: 0.8641Epoch 00007: val_loss improved from 0.74828 to 0.68810, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.6382 - acc: 0.8645 - val_loss: 0.6881 - val_acc: 0.8383
Epoch 9/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.5825 - acc: 0.8754Epoch 00008: val_loss improved from 0.68810 to 0.64588, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.5819 - acc: 0.8756 - val_loss: 0.6459 - val_acc: 0.8395
Epoch 10/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.5400 - acc: 0.8803Epoch 00009: val_loss improved from 0.64588 to 0.61251, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.5402 - acc: 0.8799 - val_loss: 0.6125 - val_acc: 0.8455
Epoch 11/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.5050 - acc: 0.8845Epoch 00010: val_loss improved from 0.61251 to 0.58934, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.5043 - acc: 0.8849 - val_loss: 0.5893 - val_acc: 0.8515
Epoch 12/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.4757 - acc: 0.8895Epoch 00011: val_loss improved from 0.58934 to 0.57236, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.4762 - acc: 0.8894 - val_loss: 0.5724 - val_acc: 0.8503
Epoch 13/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.4529 - acc: 0.8947Epoch 00012: val_loss improved from 0.57236 to 0.55120, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.4527 - acc: 0.8948 - val_loss: 0.5512 - val_acc: 0.8515
Epoch 14/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.4316 - acc: 0.8983Epoch 00013: val_loss improved from 0.55120 to 0.54464, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.4314 - acc: 0.8985 - val_loss: 0.5446 - val_acc: 0.8575
Epoch 15/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.4134 - acc: 0.9024Epoch 00014: val_loss improved from 0.54464 to 0.53171, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.4131 - acc: 0.9024 - val_loss: 0.5317 - val_acc: 0.8515
Epoch 16/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3968 - acc: 0.9069Epoch 00015: val_loss improved from 0.53171 to 0.51702, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3964 - acc: 0.9072 - val_loss: 0.5170 - val_acc: 0.8491
Epoch 17/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3819 - acc: 0.9072Epoch 00016: val_loss improved from 0.51702 to 0.51263, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3821 - acc: 0.9073 - val_loss: 0.5126 - val_acc: 0.8503
Epoch 18/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3692 - acc: 0.9102Epoch 00017: val_loss improved from 0.51263 to 0.50509, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3691 - acc: 0.9102 - val_loss: 0.5051 - val_acc: 0.8503
Epoch 19/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3556 - acc: 0.9144Epoch 00018: val_loss improved from 0.50509 to 0.49593, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3558 - acc: 0.9142 - val_loss: 0.4959 - val_acc: 0.8503
Epoch 20/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3450 - acc: 0.9183Epoch 00019: val_loss improved from 0.49593 to 0.49012, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3448 - acc: 0.9183 - val_loss: 0.4901 - val_acc: 0.8539
Epoch 21/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3341 - acc: 0.9180Epoch 00020: val_loss improved from 0.49012 to 0.48517, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3351 - acc: 0.9178 - val_loss: 0.4852 - val_acc: 0.8539
Epoch 22/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3250 - acc: 0.9222Epoch 00021: val_loss improved from 0.48517 to 0.48446, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3247 - acc: 0.9225 - val_loss: 0.4845 - val_acc: 0.8467
Epoch 23/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3154 - acc: 0.9231Epoch 00022: val_loss improved from 0.48446 to 0.48064, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.3158 - acc: 0.9229 - val_loss: 0.4806 - val_acc: 0.8587
Epoch 24/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.3073 - acc: 0.9239Epoch 00023: val_loss improved from 0.48064 to 0.46919, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.3069 - acc: 0.9241 - val_loss: 0.4692 - val_acc: 0.8527
Epoch 25/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.2987 - acc: 0.9279Epoch 00024: val_loss improved from 0.46919 to 0.46755, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.2989 - acc: 0.9280 - val_loss: 0.4676 - val_acc: 0.8563
Epoch 26/30
6640/6680 [============================>.] - ETA: 0s - loss: 0.2916 - acc: 0.9315Epoch 00025: val_loss improved from 0.46755 to 0.46689, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.2911 - acc: 0.9314 - val_loss: 0.4669 - val_acc: 0.8611
Epoch 27/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.2826 - acc: 0.9308Epoch 00026: val_loss improved from 0.46689 to 0.46163, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.2829 - acc: 0.9307 - val_loss: 0.4616 - val_acc: 0.8563
Epoch 28/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.2765 - acc: 0.9333Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.2762 - acc: 0.9335 - val_loss: 0.4622 - val_acc: 0.8551
Epoch 29/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.2697 - acc: 0.9362Epoch 00028: val_loss improved from 0.46163 to 0.46122, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 4s - loss: 0.2694 - acc: 0.9362 - val_loss: 0.4612 - val_acc: 0.8551
Epoch 30/30
6660/6680 [============================>.] - ETA: 0s - loss: 0.2627 - acc: 0.9372Epoch 00029: val_loss improved from 0.46122 to 0.45912, saving model to saved_models/weights.best.XCEPTION.hdf5
6680/6680 [==============================] - 5s - loss: 0.2627 - acc: 0.9371 - val_loss: 0.4591 - val_acc: 0.8551
Out[33]:
<keras.callbacks.History at 0x7fbf600cfeb8>

Load the Model With Best Validation Loss

In [19]:
XCEPTION_model.load_weights('saved_models/weights.best.XCEPTION.hdf5')

TEST XCEPTION

In [20]:
XCEPTION_predictions = [np.argmax(XCEPTION_model.predict(np.expand_dims(feature, axis=0))) for feature in test_XCEPTION]

# report test accuracy
test_accuracy = 100*np.sum(np.array(XCEPTION_predictions)==np.argmax(test_targets, axis=1))/len(XCEPTION_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 84.9282%

INCEPTION V3

In [40]:
INCEPTIONV3_model = Sequential()
INCEPTIONV3_model.add(GlobalAveragePooling2D(input_shape=train_INCEPTIONV3.shape[1:]))
INCEPTIONV3_model.add(Dense(133, activation='softmax'))

INCEPTIONV3_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_5 ( (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________

COMPILE INCEPTION V3

In [41]:
INCEPTIONV3_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

TRAIN INCEPTION V3

In [42]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.INCEPTIONV3.hdf5', 
                               verbose=1, save_best_only=True)

INCEPTIONV3_model.fit(train_INCEPTIONV3, train_targets, 
          validation_data=(valid_INCEPTIONV3, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6580/6680 [============================>.] - ETA: 0s - loss: 1.1618 - acc: 0.7146Epoch 00000: val_loss improved from inf to 0.64968, saving model to saved_models/weights.best.INCEPTIONV3.hdf5
6680/6680 [==============================] - 3s - loss: 1.1554 - acc: 0.7162 - val_loss: 0.6497 - val_acc: 0.8132
Epoch 2/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.4836 - acc: 0.8527Epoch 00001: val_loss improved from 0.64968 to 0.63868, saving model to saved_models/weights.best.INCEPTIONV3.hdf5
6680/6680 [==============================] - 2s - loss: 0.4817 - acc: 0.8530 - val_loss: 0.6387 - val_acc: 0.8216
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.3605 - acc: 0.8902Epoch 00002: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.3600 - acc: 0.8903 - val_loss: 0.6529 - val_acc: 0.8455
Epoch 4/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.3004 - acc: 0.9070Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.2981 - acc: 0.9075 - val_loss: 0.6733 - val_acc: 0.8455
Epoch 5/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.2406 - acc: 0.9222Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.2407 - acc: 0.9223 - val_loss: 0.7234 - val_acc: 0.8563
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.1987 - acc: 0.9354Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1982 - acc: 0.9356 - val_loss: 0.7260 - val_acc: 0.8371
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.1640 - acc: 0.9467Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1638 - acc: 0.9467 - val_loss: 0.8182 - val_acc: 0.8323
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1424 - acc: 0.9536Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1413 - acc: 0.9539 - val_loss: 0.7328 - val_acc: 0.8503
Epoch 9/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.1224 - acc: 0.9597Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1220 - acc: 0.9597 - val_loss: 0.7450 - val_acc: 0.8479
Epoch 10/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.1027 - acc: 0.9670Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1062 - acc: 0.9668 - val_loss: 0.8123 - val_acc: 0.8527
Epoch 11/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0914 - acc: 0.9708Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0912 - acc: 0.9707 - val_loss: 0.8191 - val_acc: 0.8551
Epoch 12/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0798 - acc: 0.9750Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0800 - acc: 0.9749 - val_loss: 0.7874 - val_acc: 0.8515
Epoch 13/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0700 - acc: 0.9771Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0693 - acc: 0.9774 - val_loss: 0.8320 - val_acc: 0.8587
Epoch 14/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0625 - acc: 0.9806Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0619 - acc: 0.9807 - val_loss: 0.8818 - val_acc: 0.8539
Epoch 15/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0575 - acc: 0.9829Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0570 - acc: 0.9831 - val_loss: 0.8860 - val_acc: 0.8491
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0463 - acc: 0.9852Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0469 - acc: 0.9852 - val_loss: 0.8679 - val_acc: 0.8527
Epoch 17/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0424 - acc: 0.9868Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0438 - acc: 0.9864 - val_loss: 0.9290 - val_acc: 0.8455
Epoch 18/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0401 - acc: 0.9865Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0403 - acc: 0.9864 - val_loss: 0.9596 - val_acc: 0.8467
Epoch 19/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0341 - acc: 0.9892Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0337 - acc: 0.9894 - val_loss: 0.9626 - val_acc: 0.8479
Epoch 20/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0291 - acc: 0.9913Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0296 - acc: 0.9912 - val_loss: 1.0023 - val_acc: 0.8443
Out[42]:
<keras.callbacks.History at 0x7f8fd0139ba8>

Load the Model with the Best Validation Loss

In [43]:
INCEPTIONV3_model.load_weights('saved_models/weights.best.INCEPTIONV3.hdf5')

TEST INCEPTION V3

In [44]:
INCEPTIONV3_predictions = [np.argmax(INCEPTIONV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_INCEPTIONV3]

# report test accuracy
test_accuracy = 100*np.sum(np.array(INCEPTIONV3_predictions)==np.argmax(test_targets, axis=1))/len(INCEPTIONV3_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 78.4689%

RESNET50

In [45]:
RESNET50_model = Sequential()
RESNET50_model.add(GlobalAveragePooling2D(input_shape=train_RESNET50.shape[1:]))
RESNET50_model.add(Dense(133, activation='softmax'))

RESNET50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_6 ( (None, 2048)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________

COMPILE RESNET50

In [46]:
RESNET50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

TRAIN RESENT50

In [47]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.RESNET50.hdf5', 
                               verbose=1, save_best_only=True)

RESNET50_model.fit(train_RESNET50, train_targets, 
          validation_data=(valid_RESNET50, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6640/6680 [============================>.] - ETA: 0s - loss: 1.6247 - acc: 0.6024Epoch 00000: val_loss improved from inf to 0.78936, saving model to saved_models/weights.best.RESNET50.hdf5
6680/6680 [==============================] - 1s - loss: 1.6212 - acc: 0.6028 - val_loss: 0.7894 - val_acc: 0.7677
Epoch 2/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.4348 - acc: 0.8677Epoch 00001: val_loss improved from 0.78936 to 0.68341, saving model to saved_models/weights.best.RESNET50.hdf5
6680/6680 [==============================] - 1s - loss: 0.4339 - acc: 0.8678 - val_loss: 0.6834 - val_acc: 0.7820
Epoch 3/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.2645 - acc: 0.9152Epoch 00002: val_loss improved from 0.68341 to 0.67917, saving model to saved_models/weights.best.RESNET50.hdf5
6680/6680 [==============================] - 1s - loss: 0.2645 - acc: 0.9153 - val_loss: 0.6792 - val_acc: 0.8132
Epoch 4/20
6420/6680 [===========================>..] - ETA: 0s - loss: 0.1689 - acc: 0.9469Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.1711 - acc: 0.9461 - val_loss: 0.6806 - val_acc: 0.8108
Epoch 5/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1213 - acc: 0.9611Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.1209 - acc: 0.9612 - val_loss: 0.6887 - val_acc: 0.8084
Epoch 6/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0888 - acc: 0.9735Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0886 - acc: 0.9737 - val_loss: 0.7001 - val_acc: 0.8060
Epoch 7/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0655 - acc: 0.9795Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0652 - acc: 0.9796 - val_loss: 0.7376 - val_acc: 0.7988
Epoch 8/20
6420/6680 [===========================>..] - ETA: 0s - loss: 0.0500 - acc: 0.9872Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0489 - acc: 0.9876 - val_loss: 0.6895 - val_acc: 0.8335
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0380 - acc: 0.9877Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0380 - acc: 0.9877 - val_loss: 0.7421 - val_acc: 0.8108
Epoch 10/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0271 - acc: 0.9936Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0270 - acc: 0.9936 - val_loss: 0.7688 - val_acc: 0.8263
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0208 - acc: 0.9947Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0207 - acc: 0.9948 - val_loss: 0.7991 - val_acc: 0.8204
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0191 - acc: 0.9950Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0191 - acc: 0.9951 - val_loss: 0.7900 - val_acc: 0.8359
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0131 - acc: 0.9970Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0131 - acc: 0.9970 - val_loss: 0.8213 - val_acc: 0.8192
Epoch 14/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0115 - acc: 0.9973Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0114 - acc: 0.9973 - val_loss: 0.7990 - val_acc: 0.8263
Epoch 15/20
6440/6680 [===========================>..] - ETA: 0s - loss: 0.0103 - acc: 0.9980Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0102 - acc: 0.9979 - val_loss: 0.7894 - val_acc: 0.8359
Epoch 16/20
6400/6680 [===========================>..] - ETA: 0s - loss: 0.0088 - acc: 0.9984Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0092 - acc: 0.9984 - val_loss: 0.8174 - val_acc: 0.8240
Epoch 17/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0080 - acc: 0.9977Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0079 - acc: 0.9978 - val_loss: 0.8535 - val_acc: 0.8251
Epoch 18/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0074 - acc: 0.9979Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0074 - acc: 0.9979 - val_loss: 0.9090 - val_acc: 0.8204
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0071 - acc: 0.9983Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0071 - acc: 0.9984 - val_loss: 0.8761 - val_acc: 0.8251
Epoch 20/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0065 - acc: 0.9988Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0064 - acc: 0.9988 - val_loss: 0.9584 - val_acc: 0.8275
Out[47]:
<keras.callbacks.History at 0x7f8fd1335f28>

Load the Model with best Validation Loss

In [48]:
RESNET50_model.load_weights('saved_models/weights.best.RESNET50.hdf5')

Test RESNET50

In [49]:
RESNET50_predictions = [np.argmax(RESNET50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_RESNET50]

# report test accuracy
test_accuracy = 100*np.sum(np.array(RESNET50_predictions)==np.argmax(test_targets, axis=1))/len(RESNET50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 80.8612%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [21]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
# from extract_bottleneck_features import *

def XCEPTION_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = XCEPTION_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [22]:
def obtain_dog_breed(img_path, actual_breed):
    predicted_dog_breed_name = XCEPTION_predict_breed(img_path)
    actual_dog_breed_name = dog_names[np.argmax(actual_breed)]
    print('Predicted Dog Breed Name', predicted_dog_breed_name)
    print('Actual Dog Breed Name', actual_dog_breed_name)
In [38]:
import random

number_of_tests = 20

for i in range(number_of_tests):
    index = random.randint(0, len(test_files))
    img = cv2.imread(test_files[index])
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(rgb)
    obtain_dog_breed(test_files[index], test_targets[index])
    plt.show()
    
Predicted Dog Breed Name American_foxhound
Actual Dog Breed Name American_foxhound
Predicted Dog Breed Name Beauceron
Actual Dog Breed Name Beauceron
Predicted Dog Breed Name Chihuahua
Actual Dog Breed Name Chihuahua
Predicted Dog Breed Name Boykin_spaniel
Actual Dog Breed Name Boykin_spaniel
Predicted Dog Breed Name Bullmastiff
Actual Dog Breed Name Bullmastiff
Predicted Dog Breed Name Norwegian_buhund
Actual Dog Breed Name Chihuahua
Predicted Dog Breed Name Great_pyrenees
Actual Dog Breed Name Great_pyrenees
Predicted Dog Breed Name Saint_bernard
Actual Dog Breed Name Saint_bernard
Predicted Dog Breed Name Kuvasz
Actual Dog Breed Name Kuvasz
Predicted Dog Breed Name Bedlington_terrier
Actual Dog Breed Name Bedlington_terrier
Predicted Dog Breed Name German_shepherd_dog
Actual Dog Breed Name German_shepherd_dog
Predicted Dog Breed Name Golden_retriever
Actual Dog Breed Name Great_pyrenees
Predicted Dog Breed Name Clumber_spaniel
Actual Dog Breed Name Clumber_spaniel
Predicted Dog Breed Name Papillon
Actual Dog Breed Name Papillon
Predicted Dog Breed Name Brussels_griffon
Actual Dog Breed Name Brussels_griffon
Predicted Dog Breed Name Italian_greyhound
Actual Dog Breed Name Italian_greyhound
Predicted Dog Breed Name Portuguese_water_dog
Actual Dog Breed Name Portuguese_water_dog
Predicted Dog Breed Name American_staffordshire_terrier
Actual Dog Breed Name American_staffordshire_terrier
Predicted Dog Breed Name Pharaoh_hound
Actual Dog Breed Name Pharaoh_hound
Predicted Dog Breed Name Newfoundland
Actual Dog Breed Name Newfoundland

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [23]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
def image_detector(img_path):
    img = cv2.imread(img_path)
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(rgb)
    
    dog = dog_detector(img_path)
    human = face_detector(img_path)
    
    if (dog == True):
        print('A Dog has been detected')
        print('Detected Dog Breed', XCEPTION_predict_breed(img_path))
        
    if (human == True):
        print('A Human has been detected')
        print('Detected Dog Breed', XCEPTION_predict_breed(img_path))
        
    if ((dog == False) and (human == False)):
        print('Neither a dog nor human were detected')
        
    plt.show()
    

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

The individual outputs can been below. I picked up all the below images from Google Images.

All the dogs are detected as dogs and the three sports starts as detected as humans.

Out of the eleven dog pictures, the dog breed has been correctly identified in ten cases.

I even tested 2 cat pictures and the algorithm correctly detetced that the pic was neither that of a dog or human.

This output is good in my opinion. I would have liked to get all the dog breed predictiosn correct. I came close; instead of detecting a German pinscher I detected a Doberman_pinscher.

Possible points of improvement for my algorithm will be to get a higher accuracy in the model. I was at 85%. When i randomly tested 20 dog images from the test set, i got 90% of them correct. Obviously i would like to improve the accuracy to above 95%. My AWS instance kept dying on me(if not i would have definitely attempted different models). So a better model/CNN would have led to a higher test accuracy. This is one area of improvement. Other improvements in the algorithm would be to detect breeds of cats. This can be extended to other pets and therafter all animals. More improvements would be with the CNN itself such as a more deeper network. In my Xception model, i didn't notice a very different result while using different optimizers such as sgd and rmsprop; i might have to do better optimizer parameter tuning. I didn't using dropout, i should try using dropout in my CNN.

In [24]:
image_detector('test_images/American_Foxhound.jpg')
A Dog has been detected
Detected Dog Breed American_foxhound
In [25]:
image_detector('test_images/Australian_Shepherd.jpg')
A Dog has been detected
Detected Dog Breed Australian_shepherd
In [26]:
image_detector('test_images/Belgian_Malinois.jpg')
A Dog has been detected
Detected Dog Breed Belgian_malinois
In [27]:
image_detector('test_images/Belgian_Malinois_1.jpg')
A Dog has been detected
Detected Dog Breed Belgian_malinois
In [28]:
image_detector('test_images/Boston_Terrier.jpg')
A Dog has been detected
Detected Dog Breed Boston_terrier
In [29]:
image_detector('test_images/DachShund.jpg')
A Dog has been detected
Detected Dog Breed Dachshund
In [30]:
image_detector('test_images/Finnish_Spitz.jpg')
A Dog has been detected
Detected Dog Breed Finnish_spitz
In [31]:
image_detector('test_images/German_Pinscher.jpg')
A Dog has been detected
Detected Dog Breed Doberman_pinscher
In [32]:
image_detector('test_images/Golden_Retriever.jpg')
A Dog has been detected
Detected Dog Breed Golden_retriever
In [33]:
image_detector('test_images/Irish_Terrier.jpg')
A Dog has been detected
Detected Dog Breed Irish_terrier
In [34]:
image_detector('test_images/Yorkshire_Terrier.jpg')
A Dog has been detected
Detected Dog Breed Yorkshire_terrier
In [35]:
image_detector('test_images/Lewis_Hamilton.jpg')
A Human has been detected
Detected Dog Breed Glen_of_imaal_terrier
In [36]:
image_detector('test_images/Lionel_Messi.jpg')
A Human has been detected
Detected Dog Breed Canaan_dog
In [37]:
image_detector('test_images/Rob_Gronkowski.jpg')
A Human has been detected
Detected Dog Breed Anatolian_shepherd_dog
In [38]:
image_detector('test_images/Norweigian_Forest_Cat.jpg')
Neither a dog nor human were detected
In [39]:
image_detector('test_images/Australian_Mist.jpg')
Neither a dog nor human were detected
In [ ]: